import { JwtModule } from '@nestjs/jwt';
import { Module, Global } from '@nestjs/common';
import { UserModule } from 'src/modules/user/user.module';
import { JwtAuthGuard } from 'src/modules/auth/jwt-auth.guard';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { getConnectionToken } from '@nestjs/mongoose';
import { Connection } from 'mongoose';

@Global() // 声明为全局模块
@Module({
  imports: [
    // ConfigModule,
    // 动态异步导入模块
    JwtModule.registerAsync({  // 处理异步配置
      imports: [ConfigModule],
      useFactory: (config: ConfigService) => ({
        secret: config.get('JWT_SECRET'),
        signOptions: { expiresIn: '15d' },
      }),
      inject: [ConfigService], // 注入的依赖
    }),
    UserModule,
  ],
  providers: [
    // 全局守卫配置
    {
      provide: 'APP_GUARD',
      useClass: JwtAuthGuard,
    },
    {
      provide: 'DATABASE_CONNECTION',
      useFactory: (connection: Connection) => connection,
      inject: [getConnectionToken()], // 默认连接
    },
  ],
  exports: [JwtModule, UserModule, 'DATABASE_CONNECTION'],
})
class GuardModule {}

@Module({
  imports: [GuardModule],
  exports: [GuardModule],
})
export class SharedModule {}
